﻿using UnityEngine;

public static class GameObjectExtensions
{
    // 销毁所有子物体
    public static void DestroyAllChildren(this GameObject source)
    {
        var childCount = source.transform.childCount;
        for (var i = 0; i < childCount; i++)
            Object.Destroy(source.transform.GetChild(i).gameObject);
    }

    /// <summary>
    ///     改变对象的层级
    /// </summary>
    /// <param name="gameobject">对象</param>
    /// <param name="layerName">层级名称</param>
    public static void ChangeLayer(this GameObject gameobject, string layerName)
    {
        var layer = LayerMask.NameToLayer(layerName);
        if (gameobject)
            foreach (var traform in gameobject.GetComponentsInChildren<Transform>(true))
                traform.gameObject.layer = layer;
    }

    /// <summary>
    ///     改变对象的层级
    /// </summary>
    /// <param name="gameobject">对象</param>
    /// <param name="layer">层级编号</param>
    public static void ChangeLayer(this GameObject gameobject, int layer)
    {
        if (gameobject)
            foreach (var traform in gameobject.GetComponentsInChildren<Transform>(true))
                traform.gameObject.layer = layer;
    }

    /// <summary>
    ///     给对象加上组件
    ///     对象身上不存在这个组件
    ///     存在则不作处理
    /// </summary>
    /// <typeparam name="T">组件</typeparam>
    /// <param name="gameObject">对象</param>
    /// <returns></returns>
    public static T AddComponentIfNotFound<T>(this GameObject gameObject) where T : Component
    {
        var component = gameObject.GetComponent<T>();

        if (component == null) component = gameObject.AddComponent<T>();

        return component;
    }

    /// <summary>
    ///     移除物体上挂载的脚本
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="gameObject"></param>
    public static void Remove<T>(this GameObject gameObject) where T : MonoBehaviour
    {
        if (gameObject.GetComponent<T>()) Object.Destroy(gameObject.GetComponent<T>());
    }
}